#include "Input.h"
Input::Input()
{
	_directInput = NULL;
	_keyBoard = NULL;
}
Input::~Input()
{
	if(_directInput != NULL)
		_directInput->Release();
	if(_keyBoard != NULL)
		_keyBoard->Release();
}
bool Input::Init_DirectInput(HINSTANCE hInst,HWND hwnd)
{
	HRESULT result = NULL;
	result = DirectInput8Create(hInst,
		DIRECTINPUT_VERSION,
		IID_IDirectInput8,
		(void **) &_directInput,
		NULL);
	if(result != DI_OK)
		return false;

	result = _directInput->CreateDevice(GUID_SysKeyboard,
		&_keyBoard,
		NULL);

	if(result != DI_OK)
		return false;

	return true;

}
bool Input::Init_Keyboard(HWND hwnd)
{
	HRESULT result = NULL;
	result = _keyBoard->SetDataFormat(&c_dfDIKeyboard);
	
	if(result != DI_OK)
		return false;

	result = _keyBoard->SetCooperativeLevel(hwnd,DISCL_NONEXCLUSIVE|DISCL_FOREGROUND);

	if(result != DI_OK)
		return false;

	result = _keyBoard->Acquire();
	if(result != DI_OK)
		return false;

	return true;
}

void Input ::Pool_Keyboard()
{
	for (int i=9; i< 256; i++)
	{
		_oldKeys[i] = _keys[i];
	}
	_keyBoard->Poll();
	_keyBoard->GetDeviceState(sizeof(_keys),(LPVOID)&_keys);
	ReAcquire();
}
void Input::ReAcquire()
{
	HRESULT result = NULL;
	_keyBoard->GetDeviceState(sizeof(_keys),(LPVOID)&_keys);
	if(FAILED(result))
	{
		result = _keyBoard->Acquire();
		if(result == DIERR_INPUTLOST)
			result = _keyBoard->Acquire();
	}
}

int Input::OnKeyDown(int key)
{
	return ((! _oldKeys[key]) && (_keys[key] & 0x80));
}

int Input::OnKeyPress(int key)
{
	return (_keys[key] & 0x80);
}
int Input::OnKeyUp(int key)
{
	return !(_keys[key] & 0x80);
}